package com.barnett.tool;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.regex.Pattern;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.text.Html;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.view.ViewTreeObserver;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.barnett.utils.L;

/**
 * TODO<基本的工具类>
 * 
 * 包括正则判断、四舍五入、对字符串的操作、全角半角、像素和dip转化
 * 
 * @author JiangJian
 * @data: 2014-6-4 上午10:33:31
 * @version: V1.0
 */
public class BaseTool {
	private final static Pattern emailer = Pattern
			.compile("\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*");

	private final static Pattern mobile = Pattern
			.compile("^(13|14|15|18)[0-9]{9}$");

	private final static Pattern telphone = Pattern
			.compile("\\d{3,4}-\\d{7,8}");

	private final static ThreadLocal<SimpleDateFormat> dateFormater = new ThreadLocal<SimpleDateFormat>() {
		@Override
		protected SimpleDateFormat initialValue() {
			return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);
		}
	};

	private final static ThreadLocal<SimpleDateFormat> dateFormater2 = new ThreadLocal<SimpleDateFormat>() {
		@Override
		protected SimpleDateFormat initialValue() {
			return new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA);
		}
	};

	private final static ThreadLocal<SimpleDateFormat> dateFormater3 = new ThreadLocal<SimpleDateFormat>() {
		@Override
		protected SimpleDateFormat initialValue() {
			return new SimpleDateFormat("yyyy-MM", Locale.CHINA);
		}
	};

	/**
	 * 输入一个小数 进行四舍五入,value是String类型的小数,newScale是新小数的规模,即保留几位小数
	 * 
	 * @param value
	 * @param newScale
	 */
	public static String BigDecimalDouble(String value, int newScale) {
		if (isEmpty(value)) {
			return "0.00";
		}
		BigDecimal mData = new BigDecimal(value).setScale(newScale,
				BigDecimal.ROUND_HALF_UP);
		return mData.toString();
	}

	/**
	 * 限制行数，超出用...代替
	 * 
	 * @param view
	 * @param maxLine
	 * @throw
	 * @return void
	 */
	public static void truncate(final TextView view, final int maxLine) {
		ViewTreeObserver vto = view.getViewTreeObserver();
		vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
			public void onGlobalLayout() {
				if (view.getLineCount() > maxLine) {
					int lineEndIndex = view.getLayout().getLineEnd(maxLine - 1);
					String text = view.getText().subSequence(0,
							lineEndIndex - 3)
							+ "...";
					view.setText(text);
				}
			}
		});
	}

	/**
	 * 全角转半角
	 * 
	 * @param input
	 * @return
	 * @throw
	 * @return String
	 */
	public static String fullWidthToHalfWidth(String s) {
		if (isEmpty(s)) {
			return s;
		}

		char[] source = s.toCharArray();
		for (int i = 0; i < source.length; i++) {
			if (source[i] == 12288) {
				source[i] = ' ';
				// } else if (source[i] == 12290) {
				// source[i] = '.';
			} else if (source[i] >= 65281 && source[i] <= 65374) {
				source[i] = (char) (source[i] - 65248);
			} else {
				source[i] = source[i];
			}
		}
		return new String(source);
	}

	/**
	 * 半角转全角
	 * 
	 * @param input
	 * @return
	 * @throw
	 * @return String
	 */
	public static String halfWidthToFullWidth(String s) {
		if (isEmpty(s)) {
			return s;
		}

		char[] source = s.toCharArray();
		for (int i = 0; i < source.length; i++) {
			if (source[i] == ' ') {
				source[i] = (char) 12288;
				// } else if (source[i] == '.') {
				// source[i] = (char)12290;
			} else if (source[i] >= 33 && source[i] <= 126) {
				source[i] = (char) (source[i] + 65248);
			} else {
				source[i] = source[i];
			}
		}
		return new String(source);
	}

	/**
	 * 判断给定字符串是否空白串。 空白串是指由空格、制表符、回车符、换行符组成的字符串 若输入字符串为null或空字符串，返回true
	 * 
	 * @param input
	 * @return boolean
	 */
	public static boolean isEmpty(String input) {
		if (input == null || input.equals("null") || "".equals(input))
			return true;

		for (int i = 0; i < input.length(); i++) {
			char c = input.charAt(i);
			if (c != ' ' && c != '\t' && c != '\r' && c != '\n') {
				return false;
			}
		}
		return true;
	}

	/**
	 * 判断是不是一个合法的电子邮件地址
	 * 
	 * @param email
	 * @return
	 */
	public static boolean isEmail(String email) {
		if (email == null || email.trim().length() == 0)
			return false;
		return emailer.matcher(email).matches();
	}

	/**
	 * 判断手机号是否合法
	 * 
	 * @param mobiles
	 * @return
	 */
	public static boolean isMobileNO(String mobiles) {
		return mobile.matcher(mobiles).matches();
	}

	/**
	 * 判断电话号码是否合法
	 * 
	 * @param telPhone
	 * @return
	 */
	public static boolean isTelPhone(String telPhone) {
		return telphone.matcher(telPhone).matches();
	}

	/**
	 * 将字符串转为日期类型（yyyy-MM-dd HH:mm:ss）
	 * 
	 * @param sdate
	 * @return
	 */
	public static Date toDate(String sdate) {
		try {
			return dateFormater.get().parse(sdate);
		} catch (ParseException e) {
			return null;
		}
	}

	/**
	 * 将字符串转为日期类型（yyyy-MM-dd）
	 * 
	 * @param sdate
	 * @return
	 */
	public static Date toDate2(String sdate) {
		try {
			return dateFormater2.get().parse(sdate);
		} catch (ParseException e) {
			return null;
		}
	}

	/**
	 * 将字符串转为日期类型（yyyy-MM）
	 * 
	 * @param sdate
	 * @return
	 */
	public static Date toDate3(String sdate) {
		try {
			return dateFormater3.get().parse(sdate);
		} catch (ParseException e) {
			return null;
		}
	}

	/**
	 * 根据手机的分辨率从dp转换成px(像素)
	 * 
	 * @param context
	 * @param dpValue
	 * @return
	 */
	public static int dip2px(Context context, float dpValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (dpValue * scale + 0.5f);
	}

	/**
	 * 根据手机的分辨率从px(像素)转换成dp
	 * 
	 * @param context
	 * @param pxValue
	 * @return
	 */
	public static int px2dip(Context context, float pxValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (pxValue / scale + 0.5f);
	}

	/**
	 * 设置指定的字符字体颜色
	 * 
	 * @param str
	 * @param start
	 * @param end
	 * @return
	 */
	public static SpannableString getColorSpan(String str, int color,
			int start, int end) {
		SpannableString msp = new SpannableString(str);
		if (start >= 0 && start < str.length() && end > start
				&& end <= str.length()) {
			// 设置字体前景色
			msp.setSpan(new ForegroundColorSpan(color), start, end,
					Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); // 设置前景色为洋红色
		}
		return msp;
	}

	/**
	 * 弹出框
	 * 
	 * @param context
	 * @param message
	 * @param onDialogListener
	 */
	public static void dialog(Context context, String message,
			final OnDialogListener onDialogListener) {
		AlertDialog.Builder builder = new Builder(context);
		builder.setMessage(message);
		builder.setTitle("提示");
		builder.setPositiveButton("确认", new OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
				onDialogListener.onDialog();
			}
		});
		builder.setNegativeButton("取消", new OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}
		});
		builder.create().show();
	}

	public interface OnDialogListener {
		public void onDialog();
	}

	/**
	 * list 弹出dialog
	 * 
	 * @param context
	 * @param items
	 * @param title
	 * @param itemDialogListener
	 */
	public static void listDialog(Context context, String[] items,
			String title, final OnItemDialogListener itemDialogListener) {
		new AlertDialog.Builder(context).setTitle(title)
				.setItems(items, new OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						dialog.dismiss();
						itemDialogListener.onDialog(which);
					}
				}).setNegativeButton("取消", null).show();
	}

	public interface OnItemDialogListener {
		public void onDialog(int which);
	}

	/**
	 * String转化为double,最多保留两位小数
	 * 
	 * @param str
	 * @return
	 */
	public static double getDoubleByString(String str) {
		if (isEmpty(str)) {
			return 0.00;
		}
		double db = Double.valueOf(BigDecimalDouble(str, 2));
		L.i("db", db + "");
		return db;
	}

	/**
	 * String转化为double+"",保留两位小数
	 * 
	 * @param str
	 * @return
	 */
	public static String getDoubleStrByString(String str) {
		if (isEmpty(str)) {
			return "0.00";
		}
		return BigDecimalDouble(str, 2);
	}

	/**
	 * String 转为 float,保留两位小数
	 * 
	 * @param str
	 * @return
	 */
	public static float getFloatByString(String str) {
		if (isEmpty(str)) {
			return 0f;
		}
		return Float.valueOf(BigDecimalDouble(str, 2));
	}

	/**
	 * String 转为long
	 * 
	 * @param str
	 * @return
	 */
	public static long getLongByString(String str) {
		if (isEmpty(str)) {
			return 0;
		}
		long data = Long.valueOf(str);
		return data;
	}

	/**
	 * 把照片处理为圆图
	 * 
	 * @param bitmap
	 * @return
	 */
	public static Bitmap getRoundedCornerBitmap(Bitmap bitmap) {
		Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
				bitmap.getHeight(), Config.ARGB_8888);

		int width = bitmap.getWidth();
		int height = bitmap.getHeight();

		int length = width < height ? width : height;

		Canvas canvas = new Canvas(output);

		final int color = 0xff424242;
		final Paint paint = new Paint();
		final Rect rect = new Rect(width / 2 - length / 2, height / 2 - length
				/ 2, width / 2 + length / 2, height / 2 + length / 2);
		final RectF rectF = new RectF(rect);
		final float roundPx = length / 2;

		paint.setAntiAlias(true);
		canvas.drawARGB(0, 0, 0, 0);
		paint.setColor(color);
		canvas.drawRoundRect(rectF, roundPx, roundPx, paint);

		paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
		canvas.drawBitmap(bitmap, rect, rect, paint);
		return output;
	}

	/** 根据名字从drawable获取图片资源 */
	public static Drawable getResourceId(Context context, String picName) {
		String pkName = context.getPackageName();
		L.i("pkName", pkName);
		L.i("source", picName);
		int resid = context.getResources().getIdentifier(picName, "drawable",
				pkName);
		L.i("resid", resid + "");
		Drawable drawable = context.getResources().getDrawable(resid);
		return drawable;
	}

	/**
	 * edit的错误提示框
	 * 
	 * @param editText
	 * @param msg
	 */
	public static void editError(EditText editText, String msg) {
		editText.setFocusable(true);
		editText.setFocusableInTouchMode(true);
		editText.requestFocus();
		CharSequence html = Html.fromHtml("<font color='blue'>" + msg
				+ "</font>");
		editText.setError(html);
	}

	private static Toast mToast;

	/** Toast提示 */
	public static void showToast(Context context, String text) {
		if (mToast == null) {
			mToast = Toast.makeText(context.getApplicationContext(), text,
					Toast.LENGTH_SHORT);
		} else {
			mToast.setText(text);
		}
		mToast.show();
	}

	/** TextView 中间加横线 */
	public static void strikeThruText(TextView textView) {
		// 中间加横线
		textView.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
	}

	/** 拨打电话-跳到拨号页 isCall是否直接拨号 */
	public static void callByTeleNum(Context context, String num, boolean isCall) {
		if (isEmpty(num)) {
			showToast(context, "号码为空");
			return;
		}
		Intent telIntent;
		if (isCall) {
			telIntent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + num));
		} else {
			telIntent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + num));
		}
		// 启动
		context.startActivity(telIntent);
	}

	/**
	 * string 转化为 date
	 * 
	 * @param time
	 * @return
	 */
	public static Date strToDate(String time) {
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",
				Locale.getDefault());
		try {
			date = sdf.parse(time);
			return date;
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return date;
	}
}
